//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.IO;
using OpenLS.Spreadsheet.Expressions;

namespace OpenLS.Spreadsheet.Formats.Biff.Tokens
{
    internal sealed class ArrayFormulaReferenceToken : FormulaToken
    {
        private ushort _column;
        private ushort _row;

        public ArrayFormulaReferenceToken(ushort row, ushort column)
        {
            _row = row;
            _column = column;
        }

        public ArrayFormulaReferenceToken()
        {
        }

        public override ushort GetLength(FormulaReadContextType formulaReadContextType)
        {
            return 4;
        }

        internal override void ReadContent(FormulaReadContext context)
        {
            _row = context.ReadUInt16();
            _column = context.ReadUInt16();
        }
        public override void WriteContent(FormulaWriteContext context)
        {
            context.WriteUInt16(_row);
            context.WriteUInt16(_column);
        }

        public override FormulaTokenId TokenId
        {
            get { return FormulaTokenId.Exp; }
        }

        

        internal override Expression GetExpression(FormulaEvaluationContext context)
        {
            CellAddress address = new CellAddress(_row, _column);
            if (context.WorksheetContext.ArrayFormulas.ContainsKey(address))
            {
                var exp = context.WorksheetContext.ArrayFormulas[new CellAddress(_row, _column)];
                return new ArrayFormulaReference(exp);
            }
            SharedExpression other = context.WorksheetContext.SharedFormulas[address];
            return new SharedExpressionReference(other, context.Target);
        }
    }
}
